package com.fmob.client.app.receiver;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.preference.PreferenceManager;
import android.text.TextUtils;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import sdk.webview.fmc.com.fmcsdk.activity.H5Activity;
import sdk.webview.fmc.com.fmcsdk.app.AppManager;
import sdk.webview.fmc.com.fmcsdk.base.BaseData;
import sdk.webview.fmc.com.fmcsdk.base.UserApi;
import sdk.webview.fmc.com.fmcsdk.util.Constant;
import sdk.webview.fmc.com.fmcsdk.util.Url;
import sdk.webview.fmc.com.fmcsdk.util.UserHelper;
import sdk.webview.fmc.com.fmcsdk.util.Utility;
import sdk.webview.fmc.com.fmcsdk.util.XLog;
import sdk.webview.fmc.com.fmcsdk.util.retrofit2.observer.ApiFactory;

/**
 * 点击自定义通知栏接收广播做跳转
 * Created by ydm on 2017/12/21.
 */

public class NotificationBroadcastReceiver  extends BroadcastReceiver   {
    private SharedPreferences defaultSharedPreferences;
    private String messageReceipt="false";//是否需要回执消息
    private String messageId;//消息ID
    private String messageUrl;//打开消息要跳转的URL
    public static final String TOKEN_ERROR_STATUS = "401";//token失效
    private Context context;
    @Override
    public void onReceive(Context context, Intent intent) {
        this.context = context;
        XLog.i("小米点击了通知栏",context);
        defaultSharedPreferences = PreferenceManager.getDefaultSharedPreferences(context);
        String action = intent.getAction();
        //判断当前程序是否还有activity在运行
        int activitySize = AppManager.getAppManager().getActivitySize();
        //获取消息数据
        messageId = intent.getStringExtra("messageId");
        messageReceipt = intent.getStringExtra("messageReceipt");
        messageUrl = intent.getStringExtra("messageUrl");
        XLog.i("action="+action,context);
        //r如果点击了消息
        if (action.equals("notification_clicked")) {
            if (!defaultSharedPreferences.getBoolean(Constant.ISLOGIN,false)){
                XLog.i("ISLOGIN=",context);
                return;
            }
            //消息已读
            if (!TextUtils.isEmpty(UserHelper.getToken())) {
                messageRead();
            }
            XLog.i("activitySize="+activitySize,context);
            //如果app没有activity在运行了则程序打开APP并跳转到H5界面
            if (activitySize==0){
                String packageName = context.getApplicationInfo().packageName;
                Intent launchIntent = context.getPackageManager().getLaunchIntentForPackage(packageName);
                defaultSharedPreferences.edit().putBoolean(Constant.ACTIVITY_IS_EXIST,false).apply();
                defaultSharedPreferences.edit().putString(Constant.MESSAGEURL,messageUrl).apply();
                launchIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
                context.startActivity(launchIntent);
            }else {

                //如果有已存在的H5界面，将其关闭。
//                boolean activityExist = AppManager.isActivityExist(H5Activity.class);
//                if (activityExist){
//                    AppManager.getAppManager().finishActivity(H5Activity.class);
//                }
                //直接打开H5界面
                defaultSharedPreferences.edit().putBoolean(Constant.ACTIVITY_IS_EXIST,true).apply();
                if (!TextUtils.isEmpty(UserHelper.getToken())) {
                    Intent intents = new Intent();
                    intents.putExtra(Constant.H5_TITLE, "推送消息");
                    intents.putExtra(Constant.HIDE_HEADER, false);
                    //如果消息url为空跳转到待办任务列表
                    XLog.i("messageUrl="+messageUrl,context);
                    if (TextUtils.isEmpty(messageUrl)) {
                        String address = defaultSharedPreferences.getString(Constant.BASE_ADDRESS_URL, "") + "/h5/mytask?accessToken=" + UserHelper.getToken()+"#/myMessage";
                        intents.putExtra(Constant.H5_URL, address);
                    }else {
                        intents.putExtra(Constant.H5_URL, messageUrl);
                    }
                    intents.setClass(context, H5Activity.class);
                    intents.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                    context.startActivity(intents);
                }
            }
        }

    }


    /**
     * 消息已读的接口，点击消息调用
     */
    private void messageRead() {
        ApiFactory.getFactory().create(UserApi.class).sendMessageRead(defaultSharedPreferences.getString(Constant.BASE_ADDRESS_URL,"")+ Url.H5_MESSAGE_READ, Url.XMLHTTPREQUEST, UserHelper.getToken(), UserHelper.getUserId(),Long.parseLong(messageId))
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<BaseData>() {
                    @Override
                    public void onCompleted() {
                    }
                    @Override
                    public void onError(Throwable e) {
                    }
                    @Override
                    public void onNext(BaseData result) {
                        //如果token过期，重新获取
                        if (result.getStatus().equals(Url.TOKEN_ERROR_STATUS)||result.getStatus().equals(Url.TOKEN_FORBIDDEN)){
                            XLog.i("点击推送消息token过期");
                            Utility.startLoginActivity(context);
                        }
                    }
                });
    }


}
